Home Java Docker
Home     Java

Java Topic

What is Java
History of Java
Freature of Java
Difference Between Java & C++
Java Environment Set Up
Java Hello World Program & its Internal Process
Java Hello World Program
JDK, JRE and JVM
Java Variables
Java Data Types & Unicode System
Java Operators
Java Keywords
Java Control Statements
Java if else
Java switch
Java for loop
Java While loop
Java Do While loop
Java break
Java continue
Java Oops Concept
Java Object & Class
Java Method
Java Constructor
Java Static Keyword
Java this Keyword
Java Inheritance
Java Hybrid Inheritance
Aggregation(HAS-A)
Java Polymorphism
Java method overloading
Java method overriding
Java Runtime polymorphism
Java Dynamic Binding
Super keyword
Final keyword
Difference Between method overloading and method overriding
Java Abstraction
Java Interface
Abstract class vs Interface
Java Encapsulation
Java Package
Java Access Modifiers
covariant return type
Instance initializer block
Java instanceof operator
Object Cloning in Java
Wrapper classes in Java
Java Strictfp Keyword
Recursion in Java
Java Command Line Arguments
Difference between object and class
Java String
Java String Class
Java Immutable String
Java Immutable Class
String Buffer
String Builder
String Buffer vs String
String Builder vs String Buffer
String Tokenizer in Java
Java Array
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
Java Multithreading
Lifecycle and States of a Thread in Java
How to create a thread in Java
Thread Scheduler in Java
Sleeping a thread in Java
Calling run() method
Joining a thread in Java
Naming a thread in Java
Thread Priority
Daemon Thread
Thread Pool
Thread Group
Shutdown hook
Multitasking vs Multithreading
Garbage Collection
RunTime Class
Java Synchronization
Synchronized block in Java
Static Synchronization in Java
Deadlock in Java
Inter Thread Communication in Java
Interrupting Thread in Java
Reentrant Monitor in Java
Java Applet
Animation in Applet
EventHandling in Applet
Display image in Applet
Displaying Graphics in Applet
Parameter in Applet
Java 8 Features
Java Lambda Expressions
Method References
Functional Interfaces
Java 8 Stream
Base64 Encode Decode
Default Method
for Each() Method
Collectors class
String Joiner Class
Optional Class
JavaScript Nashron
Parallel Array Sort
Type Interface
Parameter Reflection
Type and Repeating Annotations
JDBC Improvements

Java Exception Handling

  • Exception handling in Java offers a highly effective mechanism for addressing and managing runtime failures, ensuring the smooth execution of an application. Developers and programmes can efficiently handle a variety of exceptions, including ClassNotFoundException, IOException, SQLException, RemoteException, and others, by using Java's robust exception handling framework.
    • Understanding the significance of exceptions, which are unexpected disruptions during program execution, is vital. These disruptions have the potential to disrupt the normal flow of instructions within a program. To mitigate their impact, Java provides a comprehensive exception handling system.
    • The software or code is able to recognise and deal with exceptions when they occur within a method. This involves the creation of an object known as the exception object. The exception object encapsulates essential information about the exception, including its name, description, and the program's state at the time of occurrence.
Table Of Content

  • Exception handling in Java
  • Why exception Occurs
  • Types of Exceptions in Java
  • Java Exception Keywords
  • Example of Exception Handling
  • Methods to print the Exception information






  • The Java virtual machine (JVM) running out of memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc. are examples of unrecoverable circumstances that are represented by errors. The majority of the time, faults are out of the programmer's control, thus we shouldn't try to handle them.
  • Error : A serious issue that a reasonable application shouldn't attempt to catch is indicated by an error.
  • Exception : Exception denotes circumstances that a logical application might try to catch.

Why exception Occurs

  • Incorrect user data
  • System failure
  • Network connection failure
  • Try to open unavailable file
  • Error in code

Exception Hierarchy


All exception and error types are subclasses of the base class of the hierarchy, Throwable. Exception is in charge of one branch. This class is used to represent exceptional conditions that user programs should be aware of. An example of such an exception is NullPointerException. Another branch, Error, is used by the Java run-time system (JVM) to indicate run-time environment errors (JRE).






StringTokenizer

Types of Exceptions in Java


Java defines several exception types that are related to its various class libraries. Users can also define their own exceptions in Java.


There are two types of exceptions.

  • Built-in Exceptions
    • Checked Exception : Checked exceptions are classes that inherit the Throwable class, excluding RuntimeException and Error. For instance, IOException, SQLException, and so on. Compile-time checks are performed on checked exceptions.
    • Unchecked Exception : Unchecked exceptions in Java are a category of classes that extend the RuntimeException class. Examples of unchecked exceptions are ArithmeticException, NullPointerException, and ArrayIndexOutOfBoundsException, checked exceptions, which are validated during compilation, where as unchecked exceptions are detected and handled during runtime.
  • User-Defined Exceptions : Java's built-in exceptions are sometimes unable to describe a specific situation. In such cases, users can also create exceptions, which are called 'user-defined Exceptions'.



Types of Java Exceptions

Java Exception Keywords

Java provides five keywords for dealing with exceptions are mention below


Keyword Description
try The "try" keyword is used to specify a block where an exception code should be placed. That means we can't just use the try block. The try block must be followed by a catch or finally block.
catch The exception is dealt with using the "catch" block. It is essential to include a try block before using a catch block. Additionally, the finally block can be utilized to execute code that should follow the try-catch block
throw To throw an exception, we use the "throw" keyword.
throws To specify exceptions, use the "throws" keyword. It makes clear that the method could encounter an exception. No exception is thrown by it. It is constantly utilized with method signatures.
finally The program's necessary code is executed using the "finally" block. Whether or not an exception is handled, it is still executed.

Example of Exception Handling





 
public class Main {	
    public static void main(String args[]){  		 
	  try{  
	      int Num=50/0;  //code inside try block may raise exception
	   }
	  catch(ArithmeticException e){
		   System.out.println(e);
	  }   // code below catch block will execute normally
      System.out.println("This Code is unaffected to exception handling");  
   } 
}

A try-catch block is used to handle an ArithmeticException that is raised by 50/0.

Output:

java.lang.ArithmeticException: / by zero
This Code is unaffected to exception handling 


Methods to print the Exception information


1. printStackTrace() : The format of the information printed by this method for exceptions is Name of the exception, Description of the exception, and Stack Trace.


package DockerTpoint;
public class Main {	
    public static void main(String args[]){  		 
	  try{  
	      int Num=10/0;  //code inside try block may raise exception
	      System.out.println(Num);
	   }
	  catch(ArithmeticException e){
		  e.printStackTrace();
	  }   // code below catch block will execute normally
      System.out.println("This Code is unaffected to exception handling");  
   } 
}



Output:

 java.lang.ArithmeticException: / by zero
	at HELLO/DockerTpoint.Main.main(Main.java:5)
This Code is unaffected to exception handling 


2. toString() : The format of the information printed by this method is Name of the exception.


package DockerTpoint;
public class Main {	
    public static void main(String args[]){  		 
	  try{  
	      int Num=10/0;  //code inside try block may raise exception
	      System.out.println(Num);
	   }
	  catch(ArithmeticException e){
		  System.out.println(e.toString());
	  }   // code below catch block will execute normally
      System.out.println("This Code is unaffected to exception handling");  
   } 
}



Output:

 java.lang.ArithmeticException: / by zero
This Code is unaffected to exception handling 


3. getMessage() : Only the exception description is printed using this method.


package DockerTpoint;
public class Main {	
    public static void main(String args[]){  		 
	  try{  
	      int Num=10/0;  //code inside try block may raise exception
	      System.out.println(Num);
	   }
	  catch(ArithmeticException e){
		  System.out.println(e.getMessage());
	  }   // code below catch block will execute normally
      System.out.println("This Code is unaffected to exception handling");  
   } 
}



Output:

 / by zero
This Code is unaffected to exception handling 

Common Java Exceptions Scenarios


  • Any number divided by zero results in an ArithmeticException.

  • public class Main {	
        public static void main(String args[]){  		 
    	  try{  
    	      int Num=50/0;  //code inside try block may raise exception
    	   }
    	  catch(ArithmeticException e){
    		   System.out.println(e);
    	  }   // code below catch block will execute normally
          System.out.println("This Code is unaffected to exception handling");  
       } 
    }
    
    


    Output:

    java.lang.ArithmeticException: / by zero
    This Code is unaffected to exception handling 


  • Any operation on a variable that contains a null value will result in a NullPointerException.

  • public class Main {	
        public static void main(String args[]){  		 
    	  try{  
    		  String str=null;   //code inside try block may raise exception
    	      System.out.println(str.length());
    	   }
    	  catch( NullPointerException e){
    		  System.out.println(e.getMessage());
    	  }   // code below catch block will execute normally
          System.out.println("This Code is unaffected to exception handling");  
       } 
    }
    


    Output:

    Cannot invoke "String.length()" because "str" is null
    This Code is unaffected to exception handling 

  • NumberFormatException may occur if the formatting of any variable or number is inconsistent. Consider a string variable that contains characters; converting it to a digit will result in a NumberFormatException.

  • public class Main {	
        public static void main(String args[]){  		 
    	  try{  
    		  String str=null;   //code inside try block may raise exception
    		  int i=Integer.parseInt(str);
    	      System.out.println(i);
    	   }
    	  catch( NumberFormatException  e){
    		  System.out.println(e.getMessage());
    	  }   // code below catch block will execute normally
          System.out.println("This Code is unaffected to exception handling");  
       } 
    }
    


    Output:

    Cannot parse null string
    This Code is unaffected to exception handling 



  • The ArrayIndexOutOfBoundsException happens when an array is bigger than it should be. ArrayIndexOutOfBoundsException might also happen for other reasons.

  • public class Main {	
        public static void main(String args[]){  		 
    	  try{  
    		  int a[]=new int[10];     //code inside try block may raise exception
    		  a[15]=500;
    	   }
    	  catch( ArrayIndexOutOfBoundsException   e){
    		  System.out.println(e.getMessage());
    	  }   // code below catch block will execute normally
          System.out.println("This Code is unaffected to exception handling");  
       } 
    }
    


    Output:

     Index 15 out of bounds for length 10
    This Code is unaffected to exception handling                                                 


Java Try Catch block Next »
« Perv Next »


Post your comment





Read Next Topic
Java Tutorial - Topic
Java Exceptions Handling
Java Try-Catch block
Java Multiply Catch Block
Java Finally Block
Java Throws Keyword
Java Throw Keyword
Java Exception Propagation
Java Throw vs Throws
Final vs Finally vs Finalize
Exception Handling With Method Overridding
custom-exception

Read Other Java Chapter
Java Topic
Java Basic Tutorial
Java Control Statements
Java Classes & Object
Java Inheritance
Java Polymorphism
Java Abstraction
Java Encapsulation
Java OOPs Miscellaneous
Java Array
Java String
Java Exception Handling
Java Multithreading
Java Synchronization
Java Applet
Java 8 Features
Java 9 Features
Java Collection
Java Mcq
Java Interview Question
Tools
  

Useful Links

  • Home
  • Blog
  • About us
  • Contact Us
  • Privacy policy

Contact Us

Police Colony
Patna, Bihar
India

Email:

About DockerTpoint


India's largest site for Programming Tutorial as well as BANK, SSC, RAILWAY exam
and Campus placement preparation.